<?php

declare(strict_types=1);

namespace app\common\library\express;

use think\facade\Cache;
use cores\traits\ErrorTrait;
use app\common\library\helper;
use app\common\library\ApiGatewayPhpSdk202\signer;

/**
 * 快递100API模块
 * Class Kuaidi100
 * @package app\common\library\express
 */
class Kuaidi100
{
    use ErrorTrait;

    // 物流跟踪查询API地址
    //    const QUERY_URL = 'http://poll.kuaidi100.com/poll/query.do';
    const QUERY_URL = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
    const EBusinessID = '1823902';
    const ApiKey = '93b7f975-25b8-4967-91a0-503b9be04516';
    // 微信支付配置
    /* @var array $config */
    private $config;

    /**
     * 构造方法
     * WxPay constructor.
     * @param $config
     */
    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 执行查询
     * @param string $code
     * @param string $expressNo
     * @return string|bool
     */
    public function query(string $code, string $expressNo)
    {
        // 缓存索引
        $cacheIndex = "express_{$code}_$expressNo";
        if ($cacheData = Cache::get($cacheIndex)) {
            return $cacheData;
        }
        // 参数设置
        //        $postData = [
        //            'customer' => $this->config['customer'],
        //            'param' => helper::jsonEncode([
        //                'resultv2' => '1',
        //                'com' => $code,
        //                'num' => $expressNo
        //            ])
        //        ];
        //        $postData['sign'] = strtoupper(md5($postData['param'] . $this->config['key'] . $postData['customer']));

        // 组装应用级参数
        $requestData = helper::jsonEncode([
            'LogisticCode' => $expressNo,
            'ShipperCode' => 'YTO',
            'CustomerName' => '',
            'OrderCode' => ''
        ]);
        // 组装系统级参数
        $postData = array(
            'EBusinessID' => self::EBusinessID,
            'RequestType' => '1002', //免费即时查询接口指令1002/在途监控即时查询接口指令8001/地图版即时查询接口指令8003
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        );

        $postData['DataSign'] = $this->encrypt($requestData, self::ApiKey);
        // 请求快递100 api
        $result = $this->curlGet(self::QUERY_URL, $postData);
        $express = helper::jsonDecode($result);
        // 记录错误信息
        if ($express['Success'] == false) {
            $this->error = $express['message'] ?? '查询失败';
            return false;
        }
        // 记录缓存, 时效30分钟
        Cache::set($cacheIndex, $express['Traces'], 3000);
        return $express['Traces'];
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param ApiKey ApiKey
     * @return DataSign签名
     */
    private function encrypt($data, $ApiKey)
    {
        return urlencode(base64_encode(md5($data . $ApiKey)));
    }

    /**
     * curl请求指定url (post)
     * @param $url
     * @param array $data
     * @return bool|string
     */
    private function curlGet($url, array $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 将数组转换为查询字符串
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15 * 60); // 超时时间（单位：s）
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
